package com.jweb.framework.service.sqlmap.support;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：MyBatis数据库异常转换
 */
public class MyBatisExceptionTranslator implements PersistenceExceptionTranslator {
	
	private final DataSource dataSource ;
	private SQLExceptionTranslator sqlExceptionTranslator ;
	
	public MyBatisExceptionTranslator(DataSource dataSource , boolean flag){
		this.dataSource = dataSource ;
		if(!flag){
			translatorError();
		}
	}
	
	private synchronized void translatorError(){
		if(this.sqlExceptionTranslator == null){
			this.sqlExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dataSource);
		}
	}
	
	public DataAccessException translateExceptionIfPossible(RuntimeException re){
		if(re instanceof PersistenceException){
			if(re.getCause() instanceof PersistenceException){
				re = (RuntimeException) re.getCause();
			}
			if(re.getCause() instanceof SQLException){
				translatorError();
				return this.sqlExceptionTranslator.translate((new StringBuilder(String.valueOf(re.getMessage()))).append("\n").toString(), null, (SQLException)re.getCause());
			}
			else {
				return new MyBatisSystemException(re);
			}
		}
		else {
			return null ;
		}
	}
	
}
